<template>
  <div class="app-container">
    <div class="user-edit">
      <div class="user-edit-form">

        <el-form :model="formData" label-width="150px" :inline="true" :rules="rules" ref="formData">
          <div class="form-model">
            <div class="form-top">
              <i class="iconfont icon-baoxianchanpin"></i>
              <span class="form-title">
                基本信息
              </span>
            </div>
            <div class="form-info">

              <el-row :gutter="20">
                <el-col :span='12'>
                  <el-form-item label="姓 名：" class="is-required" prop="name">
                    <el-input v-model="formData.name" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                  <el-form-item label="手机号：" class="is-required" prop="phoneNumber">
                    <el-input v-model="formData.phoneNumber" maxlength='11' minlength='11' placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label="性别：">
                    <el-radio-group v-model="formData.gender">
                      <el-radio label="1">男</el-radio>
                      <el-radio label="2">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="邮箱：">
                    <el-input v-model="formData.emailAddress" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="身份证号：">
                    <el-input v-model="formData.identityCard" placeholder="请输入18位身份证号码" size="mini" class="wd230"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span='12'></el-col>
              </el-row>
              <el-row>
                <el-col :span='12'>
                  <el-form-item label="组织机构：" class="is-required" prop="belongOrganizationUnitId">

                    <!-- <el-input v-model="formData.belongOrganizationUnitId" placeholder="" size="small" class="wd230"></el-input> -->
                    <el-cascader size="mini" :value="unitId" v-model="unitId" class="wd230" :options="units" :props="unitsprops" @change="unitChange" :show-all-levels="false"></el-cascader>
                    <!-- <el-input class="hidden" type="hidden" v-model="formData.belongOrganizationUnitId"></el-input> -->
                  </el-form-item>

                </el-col>
              </el-row>
              <el-row>
                <el-col :span='12'>
                  <!-- <el-form-item label="政策级别：" class="is-required" prop="roleId">
                    <el-select v-model="roleId" placeholder="请选择" class="wd230" size="mini">
                      <el-option size="mini" v-for="item in rolelist" :key="item.id" :label="item.displayName" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item> -->
                  <el-form-item label="角色：" class="is-required" prop="roleId">
                    <el-select v-model="formData.roleId" placeholder="请选择" class="wd230" size="mini" @change='roleChange'>
                      <el-option size="mini" v-for="item in rolelist" :key="item.id" :label="item.displayName" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>

                </el-col>
                <!--<el-col :span='12'>
                  <el-form-item label="政策级别：" class="is-required" prop="policyType">
                    <el-select v-model="formData.policyType" placeholder="请选择" class="wd230" size="mini">
                      <el-option size="mini" v-for="item in policylist" :key="item.key" :label="item.value" :value="item.key">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>-->
              </el-row>
              <el-row v-if="!isEdit">
                <el-col :span='12'>
                  <el-form-item label="登录名：" class="is-required" prop="userName">
                    <el-input v-model="formData.userName" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>

                </el-col>
                <el-col :span='12'>
                  <el-form-item label="登录密码：" class="is-required" prop="password">
                    <el-input v-model="formData.password" type="password" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>

                </el-col>

              </el-row>
              <el-row>
                <el-col :span='12'>
                  <el-form-item label="账号状态：">
                    <el-radio-group v-model="formData.isActive">
                      <el-radio label="true">可用</el-radio>
                      <el-radio label="false">禁用</el-radio>
                    </el-radio-group>
                  </el-form-item>

                </el-col>
                <el-col :span='12'>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span='12'>
                  <el-form-item label="是否浏览器出单：">
                    <el-radio-group v-model="formData.isAllowBrowser">
                      <el-radio label="true">是</el-radio>
                      <el-radio label="false">否</el-radio>
                    </el-radio-group>
                  </el-form-item>

                </el-col>
                <el-col :span='12'>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span='24'>
                  <el-form-item label="权限组织：">
                    <div class="form-wd500">
                      <div class="form-inline-block" v-for="item in arryUnits" v-bind:key="item.id">
                        {{item.fullName}}
                      </div>
                    </div>
                    <el-button type="primary" icon="iconfont icon-organization" @click="openTree= true" size="mini">选择组织</el-button>
                    <el-dialog title="选择组织" :visible.sync="openTree" width="520">
                      <div class="layer-cent">
                        <el-tree check-strictly :data="organizationUnitTree" show-checkbox node-key="id" :default-expand-all='true' :default-checked-keys='defaultTree' :props="treeProps" ref="tree">
                        </el-tree>
                      </div>
                      <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="openTree = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="getCheckedKeys()">确 定</el-button>
                      </div>
                    </el-dialog>
                  </el-form-item>

                </el-col>
                <!-- <el-col :span='12'>
                  </el-col> -->
              </el-row>
            </div>
            <div class="form-top">
              <i class="iconfont icon-baoxianchanpin"></i>
              <span class="form-title">
                银行卡信息
              </span>
            </div>
            <div class="form-info">
              <el-row :gutter="20">
                <el-col :span='12'>
                  <el-form-item label="银行卡号：">
                    <el-input v-model="formData.bankCard" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                  <el-form-item label="银行：">
                    <el-select v-model="formData.bankId" placeholder="请选择" class="wd230" size="mini">
                      <el-option size="mini" v-for="item in banklist" :key="item.key" :label="item.value" :value="item.key">
                      </el-option>
                    </el-select>

                  </el-form-item>
                </el-col>
                <el-col :span='12'>
                  <el-form-item label="开户名：">
                    <el-input v-model="formData.accountName" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                  <el-form-item label="开户行：">
                    <el-input v-model="formData.openingBank" placeholder="" size="mini" class="wd230"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="center">
                <el-button type="info" size="small" @click="$router.back(-1)">取消</el-button>
                <el-button type="primary" size="small" @click="saveForm('formData')">保存</el-button>

              </el-row>
            </div>

          </div>
        </el-form>
      </div>
      <!-- <el-tree :data="data2" check-strictly='true' show-checkbox node-key="id" :default-expanded-keys="[2, 3]" :default-checked-keys="[5]" :props="defaultProps">
            </el-tree> -->
    </div>
  </div>
</template>

<script>
import { getList } from "@/api/table";

export default {
  data() {
    var checkphone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
      //setTimeout(() => {

      // if (value.length !== 11) {
      //   callback(new Error('请输入正确的手机号'));
      // } else {
      //   callback();
      // }

      //  }, 1000);
    };
    return {
      isEdit: false,
      formData: {
        isActive: "true",
        isAllowBrowser: "true"
      },
      rolelist: [], //角色下拉
      policylist: [], //政策级别
      units: [], //组织机构
      unitsprops: {
        value: "id",
        children: "organizationUnits",
        label: "displayName"
      },
      banklist: [],
      unitId: [],
      organizationUnitIds: [],
      arryUnits: [], //组织树选中数组
      AssignedRoleIds: [],
      organizationUnitTree: [],
      defaultTree: [], //默认选中tree
      openTree: false,
      roleId: "",
      defaultProps: {
        children: "children",
        label: "label"
      },
      treeProps: {
        children: "organizationUnits",
        label: "displayName"
      },
      rules: {
        name: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        phoneNumber: [
          { validator: checkphone, trigger: "blur" }
          // { required: true, min: 11, message: "请输入手机号", trigger: "blur" }
        ],
        belongOrganizationUnitId: [
          { required: true, message: "请选择组织机构", trigger: "change" }
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        policyType: [
          { required: true, message: "请选择政策", trigger: "change" }
        ],
        userName: [
          { required: !this.isEdit, message: "请输入登录名", trigger: "blur" }
        ],
        password: [
          { required: !this.isEdit, message: "请输入登录密码", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    let arr = [];
    // this.unitId=this.$route.query.id
    function dds(data, actid, pid, onid) {
      //  if (item.id == actid) {
      //     if(onid) arr.push(onid)
      //      if(pid) arr.push(pid)
      //     if(item.parentId) arr.push(item.parentId)
      //     arr.push(item.id);
      //   } else {

      //     if (item.organizationUnits !== null) {
      //       // let oneid
      //       // if(item.parentId == null){
      //       //   oneid = item.id
      //       // }
      //       dds(item.organizationUnits,actid,item.parentId,item.id)
      const me = this;
      data.map(function(item) {
        console.log(item);
        if (item.id == actid) {
          arr.push(item.id);
        } else {
          if (item.organizationUnits !== null) {
            item.organizationUnits.map(function(obj) {
              if (obj.id == actid) {
                arr.push(item.id, obj.id);
              } else {
                if (obj.organizationUnits !== null) {
                  obj.organizationUnits.map(function(elem) {
                    if (elem.id == actid) {
                      arr.push(item.id, obj.id, elem.id);
                    } else {
                      if (elem.organizationUnits !== null) {
                        elem.organizationUnits.map(function(last) {
                          if (last.id == actid) {
                            arr.push(item.id, obj.id, elem.id, last.id);
                          }
                        });
                      }
                    }
                  });
                }
              }
            });
          }
        }
      });
      console.log(arr);
      return arr;
    }
    //this.id = this.$route.params.id;
    //let routeParams = this.$route.params;
    this.loadUnits(); //组织机构
    this.loadDict(); //政策
    this.loadrole(); //角色
    this.loadNewunit(); //权限树
    this.loadbank();
    let routeParams = this.$route.query;
    if (routeParams.userId) {
      let userid = routeParams.userId;
      console.log(routeParams);
      this.isEdit = true;
      let params = { id: userid };
      this.post(params, "services/app/user/GetUserDetail").then(rs => {
        console.log(rs);

        if (rs.success) {
          let data = rs.result;
          let ndata = {
            id: data.id,
            name: data.name,
            userName: data.userName,
            emailAddress: data.emailAddress,
            phoneNumber: data.phoneNumber,
            identityCard: data.identityCard,
            gender: data.gender + "",
            isActive: data.isActive + "",
            policyType: data.policyType,
            isAllowBrowser: data.isAllowBrowser + "",
            organizationUnitIds: data.organizationUnitIds,
            accountName: data.accountName,
            bankId: data.bankId,
            openingBank: data.openingBank,
            bankCard: data.bankCard,
            belongOrganizationUnitId: data.belongOrganizationUnitId,
            roleId: data.roleId
          };
          this.roleId = data.roleId;
          let dd = [];
          dd.push(data.roleId);
          this.AssignedRoleIds = dd;
          this.unitId = dds(
            data.organizationUnitTree,
            data.belongOrganizationUnitId
          );
          this.formData = ndata;
          let treeArr = rs.result.organizationUnitTree;
          this.mapTree(treeArr);
          this.loadArry(data.organizationUnitTree)
        }
      });
    }
  },
  methods: {
    mapUnit(data, actid) {},
    mapTree(data) {
      let defaultTree = [];
      let arryUnits = [];
      function maps(data){
         data.map(function(item, index) {
          if (item.isCheck == true) {
            defaultTree.push(item.id);
            arryUnits.push(item)
          }
          console.log(item.isCheck)
          if(item.organizationUnits !== null){
           maps(item.organizationUnits)
           console.log("走没走这里2222")
          }
          
        });
      }
     maps(data)
      this.defaultTree = defaultTree;
      this.arryUnits = arryUnits;
      console.log(arryUnits)
      console.log('ssssssssssssssssss====')
    },
    cancel() {
      //取消
      this.$route.push('userment')
    },
    saveForm(formName) {
      console.log(this.formData);
      console.log(this.AssignedRoleIds);
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            user: this.formData,
            AssignedRoleIds: this.AssignedRoleIds
          };
          this.post(params, "services/app/user/CreateOrUpdateUser").then(rs => {
            if (rs.success) {
              console.log(rs);
              this.$router.push({ name: 'orgment'})
            }
          });
          console.log("33");
        } else {
          console.log("error submit!!");
          return false;
        }
      });

      console.log(this.formData);
    },
    roleChange(val) {
      //角色选择
      console.log(val);
      let arr = [];
      arr.push(val);
      this.roleId = val;
      console.log(this.roleId);
      this.AssignedRoleIds = arr;
    },
    getCheckedKeys() {
      //弹层树确定
      this.openTree = false;
      console.log(this.$refs.tree.getCheckedKeys());
      console.log(this.$refs.tree.getCheckedNodes());
      this.arryUnits = this.$refs.tree.getCheckedNodes();
      this.formData.organizationUnitIds = this.$refs.tree.getCheckedKeys();
    },
    unitChange(val) {
      let ids = val[val.length - 1];
      // this.formData.belongOrganizationUnitId = ids;
      console.log(ids);
      this.formData = Object.assign({}, this.formData, {
        belongOrganizationUnitId: ids
      });
      console.log(this.formData.belongOrganizationUnitId);
    },
    loadNewunit() {
      //组织树

      let params = [];
      this.post(params, "services/app/common/GetOrganizationUnits").then(rs => {
        console.log(rs);

        if (rs.success) {
          this.organizationUnitTree = rs.result;
          this.roletree = rs.result;
        }
      });
    },
    loadUnits() {
      //组织机构
      let params = [];
      this.post(params, "services/app/common/GetOrganizationUnits").then(rs => {
        console.log(rs);

        if (rs.success) {
          let units = rs.result;
          this.units = units;
        }
      });
    },
    loadDict(def) {
      //政策
      const me = this;
      let params = {
        id: 1
      };
      this.post(params, "services/app/common/GetDictionaries").then(rs => {
        console.log(rs);

        if (rs.success) {
          let dict = rs.result.items;
          this.policylist = dict;
        }
      });
    },
    loadrole(def) {
      //角色
      const me = this;
      let params = {};
      this.post(params, "services/app/common/GetRoles").then(rs => {
        console.log(rs);

        if (rs.success) {
          this.rolelist = rs.result.items;
        }
      });
    },
    loadbank(def) {
      //银行列表
      const me = this;
      let params = {};
      this.post(params, "services/app/common/GetBanks").then(rs => {
        console.log(rs);

        if (rs.success) {
          this.banklist = rs.result.items;
        }
      });
    },
    loadArry(data) {
      //得到true的集合
      console.log(data);
      let arryUnits = [];
      let attyUnitids = [];
      function mapTree(data){
           data.map(function(item) {
            if (item.isCheck == true) {
              arryUnits.push(item);
              attyUnitids.push(item.id);
            }
            if(item.organizationUnits!==null){
              mapTree(item.organizationUnits)
            }
            
           })
      }
      mapTree(data)
     console.log('dddddddddddddddd')
      // this.arryUnits = arryUnits;
      console.log(arryUnits);
      console.log(attyUnitids)
    }
  }
};
</script>

<style lang="scss" scoped>
.user-edit {
  padding: 34px;
  // background: #fff;
  // border: 1px solid #dddddd;
  .user-edit-form {
  }
}
.form-wd500 {
  width: 500px;
}
.form-inline-block {
  display: inline-block;
  background: #f7f7f7;
  border: 1px solid #e9e9e9;
  border-radius: 4px;
  // padding:0 23px 0 8px;
  padding: 0 8px;
  height: 23px;
  line-height: 23px;
  margin: 0 14px 15px 0;
  position: relative;
  color: #606266;
  i {
    position: absolute;
    font-size: 13px;
    right: 0px;
    top: 0px;
    padding: 1px 5px;
    cursor: pointer;
  }
}
.center {
  text-align: center;
}
.layer-cent {
  height: 250px;
  overflow-y: auto;
  padding: 0px 40px;
}
.dialog-footer {
  padding: 10px 26px 0 20px;
  border-top: 1px solid #e9e9e9;
}
.form-model {
  label {
    line-height: 28px;
  }
  .form-top {
    width: 100%;
    overflow: hidden;
    position: relative;
    i {
      color: #ee6000;
      font-size: 16px;
    }

    .form-title {
      font-size: 16px;
      color: #555;
    }
  }
  .form-top:after {
    display: block;
    height: 1px;
    width: 100%;
    position: absolute;
    left: 103px;
    top: 13px;
    background: #ddd;
    content: "";
  }
  .form-info {
    width: 100%;
    padding-top: 25px;
    .form-row {
      width: 100%;
      // display: flex;
      padding-left: 50px;

      .form-col {
        width: 440px;
        padding-bottom: 22px;
        float: left;
        .form-label {
          width: 112px;
          text-align: right;
          padding-right: 5px;
          float: left;
          font-weight: normal;
          .red {
            padding: 0 5px;
          }
        }
        .form-input {
          width: 328px;
          float: left;
          position: relative;
          height: 28px;
          .form-error {
            margin: 0;
            padding: 0;
            color: #b94a48;
            line-height: 22px;
            font-size: 12px;
            position: absolute;
            left: 0;
            bottom: -22px;
          }
        }

        .form-radio {
          display: inline-block;
          margin-right: 20px;
          line-height: 28px;
          cursor: pointer;
          i {
            font-size: 16px;
            padding-right: 7px;
            vertical-align: middle;
          }
          .icon-radio-no {
            color: #d9d9d9;
          }
          .icon-radio-yes {
            color: #108ee9;
          }
        }
        .form-inline {
          float: left;
          position: relative;
          width: 670px;
          .form-inline-block {
            display: inline-block;
            background: #f7f7f7;
            border: 1px solid #e9e9e9;
            border-radius: 4px;
            // padding:0 23px 0 8px;
            padding: 0 8px;
            height: 23px;
            line-height: 23px;
            margin: 0 14px 15px 0;
            position: relative;
            i {
              position: absolute;
              font-size: 13px;
              right: 0px;
              top: 0px;
              padding: 1px 5px;
              cursor: pointer;
            }
          }
        }
      }
      .form-colspan {
        width: auto;
      }
    }
  }
}
.form-bottom {
  width: 100%;
  height: 28px;
  text-align: center;
  padding: 100px 0 50px;
  button {
    margin: 0 20px;
  }
}
.hidden {
  display: none;
}
.layer-center {
  .util-tree {
    padding-left: 60px;
  }
}
</style>

